import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, PixelRatio, SectionList, ScrollView
} from "react-native";
import { Geolocation } from 'react-native-baidu-map';
import { API, API_GENERATE } from '../config/api';
import HTTP from '../utils/http';
import StorageHelper from '../utils/storageHelper';
import { GLOBAL } from '../config/global';
import { style } from '../theme/style';
import { STORAGE_CONSTANT } from '../config/storage';
import { PageStatusIndex } from '../component/page-status/PageStatusIndex';
import { SearchInput } from '../component/SearchInput';

const scale = GLOBAL.SCALE;
const searchLeft = require('../imgs/customer/searchLeft.png');
const requestObj = {
	keyword: "",
	pageSize: 10,
};

export class AreaListPage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		params.curCity = params.curCity ? params.curCity : '';
		const backIcon = require('../imgs/global/backGray.png');
		const backIconStyle = { width: 20 * scale, resizeMode: 'contain', marginLeft: 10 * scale }
		return {
			headerTintColor: '#404040',
			headerTitle: <SearchInput setKeyWord={(txt) => { params.setKeyWord(txt); }}
				onChangeText={() => { params.doSearch(); }}
				onSubmitEditing={() => { params.doSearch(); }}
				placeholder='搜索城市'
				inputLeftIcon={searchLeft} />,
			headerRight: (
				<Text style={{ marginRight: 10 * scale, fontSize: 12 * scale, color: '#404040' }} onPress={() => { params.doSearch() }}>搜索</Text>
			),
			headerLeft: <TouchableOpacity onPress={() => navigation.goBack()} activeOpacity={0.5}><Image source={backIcon} style={backIconStyle} /></TouchableOpacity>,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 1,
				borderBottomColor: '#E4E4E4',
				backgroundColor: '#fff',
			},
		};
	}

	constructor(props) {
		super(props);
		this.state = {
			curCity: '',
			cityData: {},
			charKeys: [],  //侧边字母
			pageStatus: {
				status: 'loading'
			},
			commonCity: [],
			checkChar: null
		}

		this._setKeyWord = this._setKeyWord.bind(this);
		this._doSearch = this._doSearch.bind(this);
		const { curCity } = this.props.navigation.state.params;
		this.paramCity = curCity;
		//requestObj.keyword = curCity;
		//this.curCity = curCity;
		this.charOffset = {};
	}

	componentWillMount () {
		this.getCityInfos();
		this.getCurCity();

	}

	componentDidMount () {
		requestObj.companyName = '';
		this.props.navigation.setParams({
			doSearch: this._doSearch,
			setKeyWord: this._setKeyWord
		});
	}

	componentWillUnmount () {
		this.timer && clearTimeout(this.timer);
	}

	getCurCity () {
		Geolocation.getCurrentPosition().then(
			(data) => {
				if (data.city) {
					this.setState({
						curCity: data.city
					})
				} else if (this.paramCity) {
					this.setState({
						curCity: this.paramCity
					})
				}
			}
		).catch(error => {
			console.log(error, 'error')
		})
	}
	/**
	 * 设置搜索关键字
	 * @param {String} txt 
	 */
	_setKeyWord (txt) {
		requestObj.keyword = txt;
	}

	async _doSearch () {
		const { pageStatus, cityData, allCity } = this.state;
		const filterCity = {};
		const keyword = requestObj.keyword.replace(/市/g, '');
		for (let key in allCity) {
			if (allCity[key] && allCity[key].length > 0) {
				filterCity[key] = [];
				allCity[key].filter(item => {
					const { areaName, pinyin } = item;
					if (areaName.includes(keyword) || pinyin.includes(keyword)) {
						filterCity[key].push(item);
					}
				});
			}
		}
		this.setState({ cityData: filterCity });
	}

	async getCityInfos () {
		//获取本地存储常用城市
		this.commonCity = await StorageHelper.get(STORAGE_CONSTANT.COMMON_CITY);
		const data = await StorageHelper.get(STORAGE_CONSTANT.ALL_CITY);
		let storgeData = JSON.parse(this.commonCity);
		if (storgeData) {
			let data = storgeData['commonCity'] || [];
			if (data && data.length > 0) {
				let set = new Set(data);  //去重
				let array = Array.from(set);   //转成数组
				this.setState({ commonCity: array });
			}
		}

		if (JSON.parse(data)) {
			this.setState({
				cityData: JSON.parse(data),
				allCity: JSON.parse(data),
				pageStatus: {
					status: 'data'
				}
			})
		} else {
			this._getCityList();
		}

	}

	async _getCityList () {
		const data = await HTTP.GET(API_GENERATE(API.GET_AREA_LIST_BY_LEVEL) + '?nodeLevel="3"');
		if (data) {
			StorageHelper.set(STORAGE_CONSTANT.ALL_CITY, data);
			this.setState({
				cityData: data,
				allCity: data,
				pageStatus: {
					status: 'data'
				}
			})
		} else {
			this.setState({
				pageStatus: {
					status: 'error',
					onErrorPress: () => {
						this.setState({
							pageStatus: {
								status: 'loading'
							}
						});
						this._getCityList();
					}
				}
			})
		}
	}

	_goAddressPage (city) {
		const { navigate } = this.props.navigation;
		const { commonCity } = this.state;
		const commonCities = {};
		const sortCity = [];

		commonCities['commonCity'] = commonCity || [];
		//存储常用城市,最多存储6个常用城市
		if (commonCities['commonCity'].length < 6) {
			commonCities['commonCity'].unshift(city);
		} else {
			commonCities['commonCity'].pop(); //删除数组最后一个项
			commonCities['commonCity'].unshift(city); //插入到数组开头
		}

		StorageHelper.set(STORAGE_CONSTANT.COMMON_CITY, commonCities);
		navigate('AddressListPage', { curCity: city });
	}

	_cell (data) {
		const sectionItem = data.item;

		return (
			<TouchableOpacity style={styles.item}
				activeOpacity={0.5} onPress={() => {
					//存储常用城市
					this._goAddressPage(sectionItem.areaName);
				}}>
				<View style={styles.right}>
					<Text style={styles.content}>{sectionItem.areaName}</Text>
				</View>
			</TouchableOpacity>

		)
	}

	_header (header) {
		return (
			<View style={styles.titleContainer}
				ref={view => {
					this.charOffset[`ref${header.section.name}`] = view;
				}}>
				<Text style={styles.title}>{header.section.name}</Text>
			</ View>
		)
	}

	render () {
		const { navigate } = this.props.navigation;
		const { pageStatus, cityData, commonCity, checkChar, curCity } = this.state;
		const sections = [];
		const charKeys = [];
		if (cityData) {
			for (let key in cityData) {
				if (cityData[key] && cityData[key].length > 0) {
					charKeys.push({ key: key.toUpperCase() });
					sections.push({ key: key.toUpperCase(), name: key.toUpperCase(), data: cityData[key] });
				}
			}
		}

		return (
			<View style={{ flex: 1 }}>
				{
					pageStatus.status === 'data' ?
						(<ScrollView ref={(view) => { this.myScrollView = view; }}>
							<View style={styles.container}>
								<View style={styles.cityContainer}>
									<Text style={styles.cityLabel}>定位</Text>
									<View style={styles.cityBox}>
										<TouchableOpacity style={styles.cityValueCon}
											activeOpacity={0.5} onPress={() => {
												this.getCurCity();
											}}>
											<Text style={styles.cityValue}>{((curCity && curCity.length > 3) ? `${curCity.substring(0, 3)}...` : curCity) || '定位失败'}</Text>
										</TouchableOpacity>

									</View>
								</View>
								{
									commonCity && commonCity.length > 0 ?
										(<View style={styles.cityContainer}>
											<Text style={styles.cityLabel}>常用城市</Text>
											<View style={styles.cityBox}>
												{
													commonCity.map((item, index) => {
														return (
															<TouchableOpacity key={index} style={styles.cityValueCon}
																activeOpacity={0.5} onPress={() => {
																	this._goAddressPage(item);
																}}>
																<Text style={styles.cityValue}>{(item && item.length > 3) ? `${item.substring(0, 4)}...` : item}</Text>
															</TouchableOpacity>)
													})
												}
											</View>
										</View>) : (null)
								}

								{
									sections.length && sections.length > 0 ?
										(
											<View style={styles.list}>
												<SectionList sections={sections}//数据源
													renderItem={this._cell.bind(this)}//cell绑定时间创建cell
													keyExtractor={(item, index) => index}//去除警告
													renderSectionHeader={this._header.bind(this)}//Header绑定时间创建表头
													scrollEnabled={true}//默认是true，false禁止滚动
													refreshing={false}
													onRefresh={() => { this._getReportList.bind(this) }}
												/>
											</View>
										) : (
											<View style={styles.noMatch}>
												<Text style={styles.noMatchText}>没有查询到该城市</Text>
											</View>
										)
								}
							</View>
						</ScrollView>)
						: (<PageStatusIndex {...pageStatus} />)   //页面状态
				}
				{
					//点击字母提示
					checkChar ?
						(<View style={styles.charTipBox}>
							<View style={styles.charTip}>
								<Text style={styles.charTipText}>{checkChar}</Text>
							</View>
						</View>)
						: (null)
				}
				{
					//侧边字母栏
					sections.length && sections.length > 0 ?
						(
							<View style={styles.charCotainer}>
								<Image style={styles.charImg} source={require('../imgs/global/blueSearch.png')} />
								{
									charKeys.map((item, index) => {
										return (
											<TouchableOpacity key={index} activeOpacity={0.5} onPress={() => {
												let layoutY;
												this.charOffset['ref' + item.key].measure((fx, fy, width, height, px, py) => {
													this.myScrollView.scrollTo({ x: 0, y: py, animated: true });
													this.setState({ checkChar: item.key });
													this.timer = setTimeout(() => {
														this.setState({ checkChar: null });
														this.timer && clearTimeout(this.timer);
													}, 2000);
												})
											}}>
												<Text style={styles.charKeys}>{item.key}</Text>
											</TouchableOpacity>
										)
									})
								}
							</View>
						) : (null)
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	searchView: {
		paddingLeft: 5 * scale,
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		width: 300 * scale,
		height: 31 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 4,
	},
	searchInput: {
		padding: 0,
		flex: 1,
		height: 31 * scale,
		fontSize: 12 * scale,
		color: '#979797',
		marginLeft: 3 * scale,
	},
	searchLeftIcon: {
		height: 13 * scale,
		width: 13 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
	},
	searchRightIcon: {
		height: 10 * scale,
		width: 10 * scale,
		marginRight: 10 * scale,
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	titleContainer: {
		backgroundColor: '#f6f6f6'
	},
	title: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
		paddingTop: 2 * scale,
		paddingBottom: 2 * scale,
		paddingLeft: 17 * scale
	},
	list: {
		position: 'relative',
	},
	item: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
		marginLeft: 17 * scale,
		marginRight: 22 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#e4e4e4'
	},
	content: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#404040'
	},
	right: {
		paddingTop: 4 * scale,
		paddingBottom: 4 * scale
	},
	charCotainer: {
		position: 'absolute',
		top: 116 * scale,
		right: 5 * scale,
	},
	charImg: {
		width: 10 * scale,
		height: 10 * scale,
		marginBottom: 3 * scale,
	},
	charKeys: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
	},
	cityContainer: {
		paddingTop: 14 * scale,
		marginLeft: 17 * scale,
		marginRight: 13 * scale,
	},
	cityLabel: {
		fontSize: 13 * scale,
		color: '#8b8b8b',
		paddingBottom: 14 * scale,
	},
	cityBox: {
		flexDirection: 'row',
		flex: 1,
		flexWrap: 'wrap',
	},
	cityValueCon: {
		width: 105 * scale,
		marginBottom: 12 * scale,
		paddingTop: 9 * scale,
		paddingBottom: 9 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 67 * scale,
		alignItems: 'center',
		marginRight: 9 * scale
	},
	cityValue: {
		fontSize: 13 * scale,
		color: '#4B4B4B',
	},
	noMatch: {
		flex: 1,
		backgroundColor: '#E9E9EF',
		alignItems: 'center',
		paddingTop: 15 * scale
	},
	noMatchText: {
		fontSize: 14 * scale,
		color: '#4B4B4B',
	},
	charTipBox: {
		position: 'absolute',
		top: 120 * scale,
		width: '100%',
		justifyContent: 'center',
		alignItems: 'center',
	},
	charTip: {
		width: 50 * scale,
		height: 50 * scale,
		backgroundColor: 'rgba(0,0, 0, .3)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	charTipText: {
		fontSize: 18 * scale,
		color: '#fff',
	}
})